<template>
	<div>
		<div class="h2">学生管理</div>
		<div id="components-form-demo-advanced-search">
			<a-form class="ant-advanced-search-form home-form" :form="form" @submit="handleSearch">
				<a-row :gutter="24">
					<a-col :span="8">
						<a-form-item label="关键字">
							<a-input autocomplete="off" class="field-right" placeholder="请输入姓名/学号搜索"
								v-decorator="[`key`]" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="诚信值">
							<div style="display: flex;">
								<a-input-number style="width: 46%;" autocomplete="off" class="field-right"
									placeholder="请输入诚信值搜索" v-decorator="[`honestyScore1`]" />~
								<a-input-number style="width: 46%;" autocomplete="off" class="field-right"
									placeholder="请输入诚信值搜索" v-decorator="[`honestyScore2`]" />
							</div>
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="年级">
							<!-- <a-input class="field-right" placeholder="请选择年级" v-decorator="[`grade`]" /> -->
							<a-date-picker mode="year" placeholder="请选择年级" format="YYYY" :value="gradeYear"
								:open="yearPickShow" @panelChange="handlePanelChange" @openChange="handleOpenChange"
								@change="yearChange" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="班级">
							<a-select :allowClear="true" v-decorator="['classID']" @search="fetchClass" placeholder="全部"
								optionFilterProp="children" showSearch>
								<a-select-option v-for="(item, index) in ClassList" :key="index" :value="item.ID">
									{{ item.Name }}</a-select-option>
							</a-select>
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="部门">
							<a-select :allowClear="true" v-decorator="['departCode']" placeholder="全部"
								optionFilterProp="children" showSearch>
								<a-select-option v-for="(item, index) in DepartCodeList" :key="index"
									:value="item.Code">{{ item.Name }}</a-select-option>
							</a-select>
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="是否为助教">
							<a-select :allowClear="true" v-decorator="['isAssistant']" placeholder="全部"
								optionFilterProp="children" showSearch>
								<a-select-option v-for="(item, index) in isAssistantList" :key="index"
									:value="item.Key">{{ item.Value }}</a-select-option>
							</a-select>
						</a-form-item>
					</a-col>
				</a-row>
			</a-form>
		</div>
		<a-button-group size="default" class="option">
			<a-button type="primary" @click="handleSearch">搜索</a-button>
			<a-button @click="handleReset">重置</a-button>
			<a-button type="primary" @click="addList">新增</a-button>
			<!-- <a-button type="primary" class="btn" @click="updataList">同步学生信息</a-button> -->
			<a-button type="primary" class="btn" @click="importList">导入</a-button>
			<a-button type="primary" @click="exportList()">导出</a-button>
			<a-button type="danger" class="btn" @click="deleteAllList">批量删除</a-button>
			<a-button type="primary" @click="updateStateList({})">修改学生状态</a-button>
		</a-button-group>
		<!-- <div class="option">
			<a-button type="primary" class="btn" @click="addList">新增</a-button>
			<a-button type="primary" class="btn" @click="updataList">同步学生信息</a-button>
			<a-button type="primary" class="btn" @click="exportList()">导出</a-button>
		</div> -->
		<div>
			<el-table ref="tableList" :data="data" v-loading="loading" border @selection-change="handleSelectionChange"
				:max-height="tableHeight" highlight-current-row style="width: 100%;">
				<el-table-column type="selection" width="55" fixed="left"></el-table-column>
				<el-table-column type="index" label="序号" width="60" fixed="left"></el-table-column>
				<el-table-column prop="Name" label="姓名" min-width="140" fixed="left">
					<template slot-scope="scope">
						<i :title="scope.row.Sex == 1 ? '男' : '女'"
							:class="{ iconfont: true, 'icon-xingbienan': scope.row.Sex == 1, 'icon-xingbienv': scope.row.Sex == 2 }"
							:style="{ color: scope.row.Sex == 1 ? 'blue' : 'red' }" @click="deleteList(scope.row)"></i>
						{{ scope.row.Name }}
					</template>
				</el-table-column>
				<el-table-column prop="UserNo" label="学号" min-width="120"></el-table-column>
				<el-table-column prop="HonestyScore" label="诚信值" min-width="120"></el-table-column>
				<el-table-column prop="ClassName" label="年级/班级" min-width="160">
					<template slot-scope="scope">
						<a-tag color="cyan">{{ scope.row.Grade }}</a-tag>
						<a-tag color="green">{{ scope.row.ClassName }}</a-tag>
					</template>
				</el-table-column>
				<el-table-column prop="DepartName" label="所属部门" min-width="120"></el-table-column>
				<el-table-column prop="IsEnable" label="状态/助教" width="280">
					<template slot-scope="scope">
						<a-tag @click="updateStateList(scope.row)" v-if="scope.row.State" :color="scope.row.State==1 ? '#87d068' : scope.row.State==2 ? '#2db7f5':scope.row.State==3 ? '#108ee9':'#f50'">
							{{ scope.row.State==1 ? '在校' : scope.row.State==2 ? '毕业':scope.row.State==3 ? '休学':'退学' }}</a-tag>
						
						<a-tag :color="scope.row.IsEnable ? 'green' : 'pink'" @click="deleteList(scope.row, 4)">
							{{ scope.row.IsEnable ? '启用' : '停用' }}</a-tag>
						<a-tag :color="scope.row.IsAssistant ? 'green' : 'pink'" @click="deleteList(scope.row, 3)">
							{{ scope.row.IsAssistant ? '助教' : '非助教' }}</a-tag>
						<!-- <a-tag :color="scope.row.IsLogin ? 'green' : 'pink'" @click="scope.row.IsLogin && deleteList(scope.row, 2)">{{ scope.row.IsLogin ? '已绑定' : '未绑定' }}</a-tag> -->
					</template>
				</el-table-column>
				<el-table-column label="操作" width="120" fixed="right">
					<template slot-scope="scope">
						<!-- <oprateBtn title="额外加分项" icon="icon-suoyouhuodong" color="green" @tap="seeList(scope.row,'ExtraScoreItem')"></oprateBtn> -->
						<oprateBtn title="修改" icon="icon-editor1" color="#1890FF"
							@tap="modifyList(scope.row, 'modify')"></oprateBtn>
						<oprateBtn title="删除" icon="icon-delete" color="red" @tap="deleteList(scope.row, 1)">
						</oprateBtn>
						<oprateBtn title="查看详细信息" icon="icon-xiangqing" color="blue"
							@tap="seeList(scope.row,'StudentManageDetail')"></oprateBtn>
						<!-- <oprateBtn title="登录该账户" icon="icon-chakan" color="green" @tap="seeList(scope.row,'registerTest')"></oprateBtn> -->
					</template>
				</el-table-column>
			</el-table>
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="pagination.currentPage" :page-sizes="pagination.pageSizeOptions"
				:page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper"
				:total="pagination.total"></el-pagination>
		</div>
		<add :text="text" :DepartCodeList="DepartCodeList" v-show="addIf" @closeFun="closeFun"></add>
		<a-modal title="提示" :visible="visible" @ok="handleOk" :confirmLoading="confirmLoading" @cancel="handleCancel">
			<a-form :form="updateForm" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }">
				<a-form-item label="学号">
					<a-input v-decorator="['userNo', { rules: [{ required: true, message: '请输入学生学号' }] }]" />
				</a-form-item>
			</a-form>
		</a-modal>
		<PersonnelImport v-show="importIf" :importText="importText" @closeFun="closeFun" />
		<updateState :text="text" :DepartCodeList="DepartCodeList" :UserNoList="UserNoList" v-show="updateStateIf" @closeFun="closeFun"/>
	</div>
</template>

<script>
	import add from './add';
	import Func from '@/utils/func';
	import moment from 'moment';
	import Cache from '@/utils/cache';
	import PersonnelImport from '@/components/PersonnelImport.vue';
	import updateState from './updateState.vue';
	import {
		GetStudentListManage,
		DeleteStudent,
		GetDepartList,
		ManageStudentDoGetManageDepartList,
		GetClassList,
		DoEnableStudent,
		CoreUpdateStudent,
		DoUnbundStudent,
		DoSetAssistantStudent
	} from '@/api/follow';
	const data = [];
	export default {
		components: {
			add,
			updateState,
			PersonnelImport
		},
		data() {
			return {
				data,
				form: this.$form.createForm(this, {
					name: 'advanced_search'
				}),
				updateForm: this.$form.createForm(this, {
					name: 'form12345'
				}),
				pagination: {
					currentPage: 1,
					pageSize: this.global.pageSize,
					pageSizeOptions: this.global.pageSizeOptions, // 每页中显示的数据
					showTotal: total => `共有 ${total} 条数据` // 分页中显示总的数据
				},
				addIf: false,
				text: {},
				visible: false,
				confirmLoading: false,
				itemId: '',
				gradeYear: null,
				yearPickShow: false,
				departmentList: [],
				worklist: [],
				loading: false,
				values: {},
				pages: {
					pageIndex: 1,
					pageSize: 20
				},
				tableHeight: parseFloat(window.innerHeight - 160),
				ClassList: [],
				UserNoList:'',
				DepartCodeList: [],
				requestUrl: this.global.requestUrl,
				token: Cache.get('token'),
				isAssistantList: this.global.isAssistantList,
				multipleSelection: [],
				importIf:false,
				importText:{},
				updateStateIf:false
			};
		},
		computed: {},
		created() {
			this.getList();
			this.getOtherList();
		},
		mounted() {},
		methods: {
			moment,
			updateStateList(row){
				if(row){
					this.text = row
					this.UserNoList = row.UserNo
				}
				this.updateStateIf = true
			},
			importList(){
				this.importText = {
					name:'学生导入',
					href:'学生导入模板.xls',
					url:'/Manage/Student/DoImport'
				},
				this.importIf = true
			},
			async fetchClass(value) {
				this.fetching = true;
				let myReg = /^[^a-zA-Z]+$/;
				if (value && value.length > 1) {
					let data = {};
					data.key = value;
					data.top = 20;
					let res = await GetClassList(data);
					this.fetching = false;
					this.ClassList = res.data.data;
				}
			},
			deleteAllList() {
				if (this.multipleSelection.length == 0) {
					this.$message.error('请先选择要删除的数据！');
				} else {
					let that = this;
					this.$confirm({
						title: '提示',
						content: '确定要删除选中的数据吗？',
						okText: '确认',
						cancelText: '取消',
						async onOk() {
							let list = that.multipleSelection;
							for (let i = 0, len = list.length; i < len; i++) {
								let data = {};
								data.id = list[i].ID;
								let res = await DeleteStudent(data);
							}
							that.getList();
						}
					});
				}
			},
			handleSelectionChange(val) {
				let arr = []
				val.forEach(item=>{
					arr.push(item.UserNo)
				})
				this.UserNoList = arr.toString()
				this.multipleSelection = val;
			},
			handleOpenChange(status) {
				this.yearPickShow = status;
			},
			handlePanelChange(value, mode) {
				this.gradeYear = moment(value).format('YYYY');
				this.yearPickShow = false;
			},
			yearChange(date, dateString) {
				if (!date) {
					this.gradeYear = null;
				}
			},
			handleSearch(e) {
				e.preventDefault();
				this.form.validateFields((error, values) => {
					this.pagination.currentPage = 1;
					this.values = values;
					if (this.gradeYear) {
						this.values.grade = this.gradeYear;
					}
					this.getList();
				});
			},
			handleReset() {
				this.form.resetFields();
				this.values = {};
				this.gradeYear = null;
				this.getList();
			},
			handleSizeChange(val) {
				this.pagination.pageSize = val;
				this.getList();
			},
			handleCurrentChange(val) {
				this.pagination.currentPage = val;
				this.getList();
			},
			async getList() {
				this.loading = true;
				let data = {};
				if (this.values) {
					data = this.values;
				}
				data.pageIndex = this.pagination.currentPage;
				data.pageSize = this.pagination.pageSize;
				let res = await GetStudentListManage(data);
				this.loading = false;
				this.data = res.data.data;
				const pagination = {
					...this.pagination
				};
				pagination.total = res.data.pageInfo.TotalItemCount;
				this.pagination = pagination;
				this.$refs.tableList.bodyWrapper.scrollTop = 0;
			},
			async getOtherList() {
				// let res = await GetClassList();
				// this.ClassList = res.data.data;
				let res1 = await ManageStudentDoGetManageDepartList();

				this.DepartCodeList = res1.data.data;
			},
			addList() {
				this.text = {};
				this.addIf = !this.addIf;
			},
			updataList() {
				this.visible = true;
			},
			async handleOk(e) {
				e.preventDefault();
				this.updateForm.validateFields(async (err, values) => {
					if (!err) {
						this.confirmLoading = true;
						let data = {};
						data = values;
						let res = await CoreUpdateStudent(data);
						if (res.data.code == 1) {
							this.$message.success(res.data.msg);
						} else {
							this.$message.error(res.data.msg);
						}
						this.updateForm.resetFields();
						this.visible = false;
						this.confirmLoading = false;
					}
				});
			},
			handleCancel(e) {
				this.visible = false;
				this.updateForm.resetFields();
			},
			modifyList(text) {
				text = Object.assign(text, {
					time: new Date()
				});
				this.addIf = !this.addIf;
				this.text = text;
			},
			deleteList(text, type) {
				let that = this;
				let content = '';
				switch (type) {
					case 1:
						content = '您确定删除该学生吗?';
						break;
					case 2:
						content = '您确定要解绑该学生的微信吗?';
						break;
					case 3:
						content = '您确定要修改该学生的助教状态吗?';
						break;
					case 4:
						content = '您确定要修改该学生的状态吗?';
						break;
					default:
						break;
				}
				this.$confirm({
					title: '提示',
					content: content,
					okText: '确认',
					cancelText: '取消',
					async onOk() {
						let data = {};
						data.id = text.ID;
						let res = type == 1 ? await DeleteStudent(data) : type == 2 ? await DoUnbundStudent(
							data) : type == 3 ? await DoSetAssistantStudent(data) : await DoEnableStudent(
							data);
						if (res.data.code == 0) {
							that.getList();
							that.$message.success(res.data.msg);
						} else {
							that.$message.error(res.data.msg);
						}
					}
				});
			},
			seeList(text, name) {
				this.$router.push({
					name: name,
					query: {
						ID: text.ID,
						Name: text.Name,
						UserNo: text.UserNo
					}
				});
			},
			exportList() {
				this.form.validateFields(async (error, values) => {
					let that = this;
					let data = {};
					this.pagination.currentPage = 1;
					this.values = values;
					if (this.gradeYear) {
						this.values.grade = this.gradeYear;
					}
					data = this.values;
					// data.key = values.key;
					// data.classID = values.classID;
					// data.departCode = values.departCode;
					// data.isAssistant = values.isAssistant;
					data.PageSize = 1;
					let res = await GetStudentListManage(data);
					if (res.data.pageInfo.TotalItemCount > 10000) {
						this.$confirm({
							title: '提示',
							content: '当前要导出的数据大于10000，耗时较久，建议您先进行搜索条件检索，再按需导出！',
							okText: '继续导出',
							cancelText: '按需导出',
							async onOk() {
								let hrefUrl = that.requestUrl +
									'Manage/Student/DoExport?userToken=' + encodeURIComponent(that
										.token)+"&schoolID="+Cache.get('myInfo')?Cache.get('myInfo').SchoolID:'';
								let hrefStr = '';
								for (let key in data) {
									if (data[key]) {
										hrefStr += key + '=' + data[key] + '&';
									}
								}
								window.open(hrefUrl + '&' + hrefStr, '_blank');
							}
						});
					} else {
						let hrefUrl = that.requestUrl + 'Manage/Student/DoExport?userToken=' +
							encodeURIComponent(that.token);
						let hrefStr = '';
						for (let key in data) {
							if (data[key]) {
								hrefStr += key + '=' + data[key] + '&';
							}
						}
						window.open(hrefUrl + '&' + hrefStr, '_blank');
					}
				});
			},
			closeFun() {
				this.addIf = false;
				this.importIf = false
				this.updateStateIf = false
				this.getOtherList()
				this.getList();
			}
		}
	};
</script>

<style lang="less" scoped>
	/deep/.ant-form-item {
		display: flex;
		margin-bottom: 10px !important;
	}

	/deep/.ant-form-item-label {
		width: 80px;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
		text-align: right;
	}

	/deep/.ant-form-item-control-wrapper {
		flex: 1;
	}

	/deep/.ant-calendar-picker {
		width: 100%;
	}
</style>
